﻿using System;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Cms.Domain;
using iLib.Web.UI;

namespace Cms.Application
{
    public class Translator
    {
        public static string GetText(string translationFile, string key, string localizationCode)
        {
            SystemContext c = GetTranslations(translationFile);
            if (!c.Keys.ContainsKey(key))
                return "[?]";
            SystemContextKey k = c.Keys[key];
            if (k.Values.ContainsKey(localizationCode))
                return k.Values[localizationCode].Trim();
            return "[?]";
        }

        private static SystemContext GetTranslations(string translationFile)
        {
            if (HttpRuntime.Cache[translationFile] == null)
            {
                var doc = new XmlDocument();
                SystemContext context;
                SystemContextKey contextKey;
                string physicalFilename;
                if (HttpContext.Current != null)
                    physicalFilename = HttpContext.Current.Server.MapPath(Url.VirtualPath + translationFile);
                else
                {
                    // We are running in test mode
                    Assembly ea = Assembly.GetExecutingAssembly();
                    string file = Path.GetDirectoryName(ea.CodeBase) + "\\" + Path.GetFileName(ea.CodeBase);
                    file = file.Substring(6);
                    file = file.Substring(0, file.LastIndexOf("\\"));
                    file = file.Substring(0, file.LastIndexOf("\\"));
                    file = file.Substring(0, file.LastIndexOf("\\"));
                    file = file.Substring(0, file.LastIndexOf("\\"));
                    physicalFilename = file + "\\Cms.Web.UI\\" + translationFile.Replace("/", "\\");
                }
                context = new SystemContext();
                if (!File.Exists(physicalFilename))
                    return context;
                doc.Load(physicalFilename);
                foreach (XmlNode key in doc.SelectNodes("/translations/key"))
                {
                    contextKey = new SystemContextKey();
                    contextKey.ID = key.Attributes["id"].Value;
                    context.Keys.Add(contextKey.ID, contextKey);
                    foreach (XmlNode value in key.ChildNodes)
                    {
                        contextKey.Values.Add(value.Attributes["localization"].Value, value.InnerText);
                    }
                }
                HttpRuntime.Cache.Insert(
                    translationFile,
                    context,
                    new CacheDependency(physicalFilename),
                    DateTime.MaxValue,
                    new TimeSpan(0, 20, 0));
            }
            return (SystemContext)HttpRuntime.Cache[translationFile];
        }
    }
}